package org.rainwalk.bill.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.rainwalk.bill.api.interceptor.AuthInterceptor;
import org.rainwalk.bill.api.log.ApiLog;
import org.rainwalk.bill.api.model.Response;
import org.rainwalk.bill.api.model.ResponseCode;
import org.rainwalk.bill.api.model.SessionUser;
import org.rainwalk.bill.entity.Bill;
import org.rainwalk.bill.entity.Category;
import org.rainwalk.bill.model.dto.CategoryAddDTO;
import org.rainwalk.bill.service.IBillService;
import org.rainwalk.bill.service.ICategoryService;
import org.rainwalk.bill.util.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户消费类别 前端控制器
 * </p>
 *
 * @author 趁雨行
 * @since 2021-02-18
 */
@Api(tags = "类别模块")
@RestController
@RequestMapping("/category")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class CategoryController {

    private final ICategoryService categoryService;

    private final IBillService billService;

    @ApiOperation("增加分类")
    @ApiLog("增加分类")
    @PostMapping
    public Response add(@RequestBody @Validated CategoryAddDTO dto, @SessionAttribute(AuthInterceptor.USER_SESSION) SessionUser sessionUser) {
        LambdaQueryWrapper<Category> query = new QueryWrapper<Category>().lambda()
                .eq(Category::getUserId, sessionUser.getId())
                .eq(Category::getCategoryName, dto.getCategoryName());
        if (this.categoryService.count(query) > 0) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "分类名称已存在");
        }

        Category category = new Category();
        category.setId(IdGenerator.generateId());
        category.setCategoryName(dto.getCategoryName());
        category.setUserId(sessionUser.getId());
        this.categoryService.save(category);
        return Response.success("添加成功", category.getId());
    }

    @ApiOperation("删除分类")
    @ApiImplicitParam(value = "类别id", name = "id", dataTypeClass = String.class, paramType = "path", required = true, example = "12435545")
    @ApiLog("删除分类")
    @DeleteMapping("/{id}")
    public Response del(@PathVariable String id, @SessionAttribute(AuthInterceptor.USER_SESSION) SessionUser sessionUser) {
        LambdaQueryWrapper<Category> delWrapper = new QueryWrapper<Category>().lambda()
                .eq(Category::getId, id)
                .eq(Category::getUserId, sessionUser.getId());
        if (!this.categoryService.remove(delWrapper)) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "找不到相关分类");
        }
        LambdaQueryWrapper<Bill> queryWrapper = new QueryWrapper<Bill>().lambda()
                .eq(Bill::getCategoryId, id);
        if (this.billService.count(queryWrapper) > 0) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "分类尚有关联账单，请处理后再删除");
        }
        return Response.success();
    }

    @ApiOperation("修改分类")
    @ApiImplicitParam(value = "类别id", name = "id", dataTypeClass = String.class, paramType = "path", required = true, example = "12435545")
    @ApiLog("修改分类")
    @PutMapping("/{id}")
    public Response edit(@PathVariable String id, @RequestBody CategoryAddDTO dto, @SessionAttribute(AuthInterceptor.USER_SESSION) SessionUser sessionUser) {
        LambdaQueryWrapper<Category> queryWrapper = new QueryWrapper<Category>().lambda()
                .eq(Category::getId, id)
                .eq(Category::getUserId, sessionUser.getId());
        if (this.categoryService.getOne(queryWrapper) == null) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "找不到相关分类");
        }
        Category category = new Category();
        category.setId(id);
        category.setCategoryName(dto.getCategoryName());
        if (!this.categoryService.updateById(category)) {
            return Response.fail(ResponseCode.SERVER_ERROR, "修改失败，请稍后重试");
        }
        return Response.success();
    }


}
